<template>
  <view class="page-orglist">
    <checkBoxTop :tabs="tabs" @handleItem="handleItem" />
    <view v-if="orgList.length > 1" class="orglist">
      <view
        class="list-item"
        :class="index === 0 && 'no-border'"
        @click="toIndex(item)"
        v-for="(item, index) in orgList"
        :key="index"
      >
        <view
          class="img-box"
          :style="{
            backgroundImage: `url(${item.logo ? file + '/file' + item.logo : ''})`,
          }"
        ></view>
        <view class="info">
          <view class="title">{{ item.name }}</view>
          <view class="msg">景区热线：{{ item.contactMobile || "-" }}</view>
          <view class="msg notice">{{
            `距您${item.distance}公里 | ${item.address || "-"}`
          }}</view>
          <view class="msg notice">{{ item.remark || "-" }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { host, file } from "@/api/config.js";
import { orgList } from "@/api/user.js";
export default {
  data() {
    return {
      host,
      file,
      active: "1",
      lats: [],
      orgList: [],
      orgListSource: [],
      tabs: [
        {
          label: "全部景区",
          key: "orgType",
          default: "1",
          options: [{ label: "全部景区", value: "1" }],
        },
        { label: "距离最近", key: "isRange" },
      ],
    };
  },
  onLoad(options) {
    uni.getLocation({
      type: "wgs84",
      success: (res) => {
        console.log("当前位置的经度：" + res.longitude);
        console.log("当前位置的纬度：" + res.latitude);
        this.lats = [res.latitude, res.longitude];
        this.getOrgList();
      },
      fail: (error) => {
        console.log(error, "====");
      },
    });
  },
  methods: {
    handleItem(data) {
      if (data.key === "isRange") {
        //排序
        this.orgList = data.value
          ? this.orgList.sort((a, b) => a.distance - b.distance)
          : JSON.parse(JSON.stringify(this.orgListSource));
      }
    },
    toIndex(row) {
      uni.setStorageSync("orgId", row?.id || "L43Q4SG4");
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/index/index?orgId=${row?.id || "L43Q4SG4"}`,
        });
      }, 100);
    },
    changeTab(e) {
      this.active = e;
    },
    toOrgIndex(row) {
      uni.setStorageSync("orgId", row?.id || "L43Q4SG4");
      uni.reLaunch({
        url: `/pages/index/index?orgId=${row?.id || "L43Q4SG4"}`,
      });
    },
    //获取org列表
    async getOrgList() {
      const res = await orgList({ currentPage: 1, pageSize: 999 });
      const result = (res.body.records || []).map((v) => {
        return {
          ...v,
          distance: this.getDistance(
            ...this.lats,
            v.latitude,
            v.longitude
          ).toFixed(1),
        };
      });
      this.orgList = result;
      this.orgListSource = JSON.parse(JSON.stringify(result));
      if(this.orgList.length === 1) {
        this.toOrgIndex(this.orgList[0])
      }
    },
    getDistance(lat1, lon1, lat2, lon2) {
      const R = 6371; // 地球半径，以千米为单位
      const dLat = this.deg2rad(lat2 - lat1);
      const dLon = this.deg2rad(lon2 - lon1);

      const a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(this.deg2rad(lat1)) *
          Math.cos(this.deg2rad(lat2)) *
          Math.sin(dLon / 2) *
          Math.sin(dLon / 2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

      const distance = R * c; // 距离，以千米为单位
      return distance;
    },
    deg2rad(d) {
      return (d * Math.PI) / 180.0;
    },
  },
};
</script>

<style lang="scss" scoped>
.page-orglist {
  height: 100%;
  overflow-y: auto;
  background-color: #fff;
}
.orglist {
  padding: 0 30rpx;
  padding-top: 100rpx;
  background-color: #fff;
  height: 100%;
  .list-item {
    display: flex;
    padding: 20rpx 0;
    border-top: 1px solid #e6e6e6;
    .img-box {
      flex-shrink: 0;
      width: 180rpx;
      height: 180rpx;
      background-color: #dbdbdb;
      border-radius: 20rpx;
      margin-right: 20rpx;
      background-size: cover;
    }
    .info {
      padding: 5rpx 0;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .title {
        font-size: 32rpx;
        color: #1a1a1a;
        font-weight: bold;
      }
      .msg {
        font-size: 22rpx;
        color: #999;
      }
      .notice {
        width: 500rpx;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
  .no-border {
    border-top: none;
  }
}
</style>
